﻿using Biotech.Log;
using project.B12.IRepository;
using project.B12.IService;
using project.B12.Model.BaseModel;
using project.B12.Model.Models;
using project.B12.Model.Res;
using software.Common.MVVM;
using software.dll.user;
using Software.Common.Util.AppConfig;

namespace project.B12.Service.UserService
{
    public partial class UserService : ObservableObject, IUserService
    {

        private readonly IPublicResource _publicResource;
        private readonly UserManager _userManager = new UserManager();
        public UserService(IPublicResource publicResource)
        {
            _publicResource = publicResource;
            _userManager.SetDirectoryPath(DataPath.UserConnectionPath);
        }
        public UserModel CurrentUser { get; set; }//当前已登录的账号

        /// <summary>
        /// 当前用户,软件启动后会更新为最后登录用户
        /// </summary>
        private string userName;
        public string UserName
        {
            get { return userName; }
            private set { userName = value; this.RaisePropertyChanged(); }
        }


        public int CurrentLockedTime { get; set; }

        private string lastUser = string.Empty;



        public string? GetConfigUserName()
        {
            if (UtilAppConfig.ExistItem("Login_Account"))
                return UserName = UtilAppConfig.GetItem("Login_Account");
            else
                return UserName = string.Empty;
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="name">账户名</param>
        /// <param name="password">密码</param>
        /// <param name="Count">是否参与错误计数</param>
        /// <returns></returns>
        public MessageModel Login(string? name, string? password, bool Count)
        {
            int LockedTimeConfig = 5;//初始化密码错误锁定次数=5
            if (UtilAppConfig.ExistItem("Login_LockedTime"))//从配置文件中获取锁定次数
                LockedTimeConfig = int.Parse(UtilAppConfig.GetAppConfig("Login_LockedTime"));
            var header = Resources.Login_SystemLogin;//系统登录
            // 账号非空检查
            if (string.IsNullOrEmpty(name))
                return MessageModel.ReturnFail(Resources.AccountEmpty, header);//账户为空，函数结束
            // 密码非空检查
            if (string.IsNullOrEmpty(password))
                return MessageModel.ReturnFail(Resources.PasswordEmpty, header);//密码为空，函数结束

            // 登录
            UserModel blLogin;
            try
            {
                if (_userManager.GetUser(name))//判断账户是否存在
                    blLogin = _userManager.GetUser(name, password);//已存在，尝试登录
                else
                    return MessageModel.ReturnFail(Resources.AccountNotExist, header);//账户不存在，函数结束
            }
            catch (Exception ex)
            {
                return MessageModel.ReturnFail(ex.Message, header);
            }

            //账密核实正确
            if (blLogin != null)
            {
                CurrentLockedTime = 0;//当前密码尝试次数归零重置

                //账户是否被锁定？
                if (blLogin.IsLocked)
                {
                    LoggerFactory.Instance.CurrentLogger.LogInfo($"用户名：({name})  尝试登录失败，因该账户目前已被禁用", "", "用户");
                    return MessageModel.ReturnFail(Resources.AccountDisabled, header);//账户已被锁定，函数结束
                }

                //账户是否已过期？
                if (blLogin.ExpirationTime != DateTime.MinValue && blLogin.ExpirationTime < DateTime.Now)
                {
                    if (!blLogin.IsLocked)//账户已过期并且锁定状态未更新
                    {
                        ChangeLockedState(blLogin);//改变账户锁定状态
                    }
                    LoggerFactory.Instance.CurrentLogger.LogInfo($"用户名：({name})  尝试登录失败，因该账户目前已过期", "", "用户");
                    return MessageModel.ReturnFail(Resources.AccountExpire, header);//账户已过期，函数结束
                }

                LoggerFactory.Instance.CurrentLogger.LogInfo(userName + "登录系统", "", "用户");
                UpdateUserName(blLogin);//更新当前软件中登录用户信息
                _publicResource.ChangeUserName(userName);

                return MessageModel.ReturnSuccess("Success", header);//登录成功！！！函数结束
            }

            //账密核实失败！
            else
            {
                //判断当前登录的用户是否有超管权限？
                if (_userManager.GetUser(name) && _userManager.GetUserRole(name)[0].Name != "超级管理员" && _userManager.GetUserRole(name)[0].Name != "厂家账号" && Count)
                {//没有超管权限
                    if (name == lastUser)//重复登录？
                        CurrentLockedTime++;
                    else//新用户登录？
                        CurrentLockedTime = 1;
                    lastUser = name;
                    if (CurrentLockedTime >= LockedTimeConfig)//尝试次数超配置范围？
                    {
                        LoggerFactory.Instance.CurrentLogger.LogInfo($"用户名：({name})  因输入密码错误次数超过{LockedTimeConfig}次，该账户已被禁用", "", "用户");
                        _userManager.UpdateUserLock(name, true);//将当前账户锁定状态更新
                        return MessageModel.ReturnFail(Resources.AccountDisabled, header);//账户锁定，函数结束
                    }
                    return MessageModel.ReturnFail(string.Format(Resources.ErrorCountPrompt, CurrentLockedTime, LockedTimeConfig), header);//未超范围，次数加一，函数结束
                }
                else//有超管权限
                    return MessageModel.ReturnFail(Resources.PasswordError, header);//警告密码错误，函数结束
            }// 登录失败
        }

        public bool IsAdmin()
        {
            if (CurrentUser == null)
                return false;
            return CurrentUser.RoleName == RoleEnum.超级管理员.ToString() || CurrentUser.RoleName == RoleEnum.厂家账号.ToString();
        }

        /// <summary>
        /// 更新当前用户
        /// </summary>
        /// <param name="user"></param>
        public void UpdateUserName(UserModel user)
        {
            UserName = user.Name;
            CurrentUser = user;

            LoggerFactory.Instance.UserName = user.Name;
            UtilAppConfig.UpdateAppConfig("Login_Account", user.Name);
            GetAllUsers();
        }

        /// <summary>
        /// 初始化
        /// </summary>
        public void Init()
        {
            GetAllDepartment();//获取部门清单
            GetRoleList();//获取角色清单
            Search_UserName = string.Empty;//搜索条件重置
            GetAllUsers();//更新用户清单
        }
    }
}
